<template>
  <div>
    <el-upload
        multiple
        :action="`${path}/fileUploadAndDownload/upload?noSave=1`"
        :on-error="uploadError"
        :on-success="uploadSuccess"
        :on-preview="handlePreview"
        :on-exceed="handleExceed"
        :show-file-list="true"
        :file-list="fileList"
        :limit="limit"
        :accept="accept"
        class="upload-btn"
    >
      <el-button type="primary">上传文件</el-button>
    </el-upload>
  </div>
</template>

<script setup>

import {ref, watch} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {useUserStore} from '@/pinia/modules/user'

defineOptions({
  name: 'UploadCommon',
})

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  limit: {
    type: Number,
    default: 3
  },
  accept: {
    type: String,
    default: ''
  },
})

const path = ref(import.meta.env.VITE_BASE_API)

const userStore = useUserStore()
const fullscreenLoading = ref(false)

const fileList = ref(props.modelValue)

const emits = defineEmits(['update:modelValue'])

watch(fileList.value, (val) => {
  console.log(val)
  emits('update:modelValue', val)
})

watch(
    () => props.modelValue,
    value => {
      fileList.value = value
    },
    {immediate: true}
)
const uploadSuccess = (res) => {
  const {data} = res
  if (data.file) {
    fileList.value.push({
      name: data.file.name,
      url: data.file.url
    })
    fullscreenLoading.value = false
  }
}

const uploadError = () => {
  ElMessage({
    type: 'error',
    message: '上传失败'
  })
  fullscreenLoading.value = false
}

// const handleRemove = (file, fileList) => {
//   console.log(file, fileList);
// }

const handlePreview = (file) => {
  console.log(file);
}

// const beforeRemove = (file) => {
//   return ElMessageBox.confirm(`确定移除 ${file.name}？`, '提示', {
//     confirmButtonText: '确定',
//     cancelButtonText: '取消',
//     type: 'warning'
//   }).then((res) => {}, (err) => {});
// }

const handleExceed = (files, fileList) => {
  ElMessageBox.alert(`当前限制选择 ${props.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
}

</script>

